package com.bible.fire.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.format.DateFormat;
import android.util.Log;

import com.bible.fire.util.AndroidUtil;
import com.bible.fire.util.SystemConstant;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

/**
 * 二维码
 * @author zhangyp
 *
 */
public class TwoDimensionCode {
	
	private static final String TAG = TwoDimensionCode.class.getSimpleName();
	
	/**
	 * 将内容编码成二维码图片，并返回图片名称
	 * @param content
	 * @return
	 */
	public static String encodeToImage(String content ){
		String path = "";
		//存储卡可用  
        if( AndroidUtil.isHasSdcard() ){
     	   String imgName = DateFormat.format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
     	  FileOutputStream fos = null;
     	  File imgDir = new File(SystemConstant.IMG_PATH_IN_SDCARD);
          if( !imgDir.exists() ){
      	    imgDir.mkdirs();
          }
	      try {		     
    	    //生成二维码图像
            Bitmap bitmap = encodeToBitmap(content, BarcodeFormat.QR_CODE, 70, 70);
            if( bitmap != null ){
            	path = SystemConstant.TWO_DIMENSION_CODE_PATH + imgName;
            	fos = new FileOutputStream( path );
            
				bitmap.compress( Bitmap.CompressFormat.JPEG, 0, fos );// 把数据写入文件           	
            }	 		    
 		  }catch (Exception e) {
 		     e.printStackTrace();
 		     Log.e(TAG, "encode error", e);
 		  }finally{
			   try {
				   fos.flush();
				   fos.close();
			   }catch(IOException e2){
				   Log.e( TAG, "file output error", e2 );
			   }
 		  }
        }
		return path;
	}
	
	public static Bitmap encodeToBitmap(String contents, BarcodeFormat format, int desiredWidth, int desiredHeight){
        final int WHITE = 0xFFFFFFFF; //可以指定其他颜色，让二维码变成彩色效果
        final int BLACK = 0xFF000000;
        Bitmap bitmap = null;
        HashMap<EncodeHintType, String> hints = null;
        String encoding = "GBK";
        if (encoding != null) {
            hints = new HashMap<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, encoding);
        }
        try {
        	MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix result = writer.encode(contents, format, desiredWidth, desiredHeight, hints);
            int width = result.getWidth();
            int height = result.getHeight();
            int[] pixels = new int[width * height];
            // All are 0, or black, by default
            for (int y = 0; y < height; y++) {
                int offset = y * width;
                for (int x = 0; x < width; x++) {
                    pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
                }
            }
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		} catch (WriterException e) {
			Log.e(TAG, "", e);
			e.printStackTrace();
		}        
        return bitmap;
    }
	
	public static String decodeBitmap(Bitmap bitmap){
		int width = bitmap.getWidth();
	    int height = bitmap.getHeight();
	    int[] pixels = new int[width * height];
	    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
	    RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
		String content = "";
		try {
            MultiFormatReader formatReader = new MultiFormatReader();
			Binarizer  binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "GBK");
			
			Result result = formatReader.decode(binaryBitmap,hints);
			content = result.getText();
			Log.d(TAG,"result = "+ result.toString());
			Log.d(TAG,"resultFormat = "+ result.getBarcodeFormat());
			Log.d(TAG,"resultText = "+ result.getText());			          
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "decode error", e);
		}
		return content;
	}
	
	/**
	 * 返回内容
	 * @param filepath
	 * @return
	 */
	public static String decodeFile(String filepath){
		
		Bitmap bitmap = BitmapFactory.decodeFile( filepath);
		if ( bitmap == null) {
		   Log.e(TAG, "Couldn't open " + filepath);
		   return "";
		}
		return decodeBitmap( bitmap );
	}

}
